//
//  QPerfectOrderInforMationVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/7.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QPerfectOrderInforMationVC.h"
#import "QPerfectOrderInforMationCell.h"
#import "QSubmitOrderModel.h"
#import "QMapLocationVC.h"
#import "QPayOrderSuccessVC.h"
#import "QConfirmOrderInforMationVC.h"
#import "QDatePickView.h"
#import "QPerfectTextViewCell.h"
#import "QChooseAddressVC.h"
#import "QOilStandardCell.h"
#import "MJExtension.h"
#import "QStandardModel.h"
#import "QPerfectOrderMoneyCell.h"
#import "QTicketPhotoView.h"
#import "HZPhotoBrowser.h"
#import "QTopupMoneyVC.h"
#import "QAddressBookVC.h"
#import "QSendCostModel.h"
#import "QNoPayOrderModel.h"
#import "CaptchaTimerManager.h"
/// iOS 9前的框架
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
/// iOS 9的新框架
#import <ContactsUI/ContactsUI.h>
#import "FileManager.h"

#import <CoreLocation/CLLocationManager.h>
#define Is_up_Ios_9             ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0  
#define Is_up_Ios_10             ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0
@interface QPerfectOrderInforMationVC ()<UITableViewDataSource,UITableViewDelegate,QStandardDelegate,HZPhotoBrowserDelegate,AddressBookActionDelegate,ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)UIActivityIndicatorView *loadingV;

@property(nonatomic,strong)UILabel *leftLabel;
@property(nonatomic,strong)UILabel *titleLabel;

@property(nonatomic,copy)NSString *paramStr;//时间
@property (nonatomic,copy)NSString * lat;//纬度
@property (nonatomic,copy)NSString * lon;//经度
@property(nonatomic,assign)CGFloat spacing;//间距
@property(nonatomic,assign)CGFloat W;//一个button的大小
@property(nonatomic,assign)CGFloat selIndex;//点击哪一个button
@property (nonatomic, copy) NSString *cityStr;//市
@property (nonatomic, copy) NSString *districtStr;//区
@property(nonatomic,assign)BOOL showKeyBoard;

@property (nonatomic,assign)int timeout;
@property (nonatomic,strong)UIButton *rightButton;


@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *phone;
@property (nonatomic,strong)NSDictionary *userAddress;
@end

@implementation QPerfectOrderInforMationVC{

    NSArray *_titleArr;//标题数组
    NSString *_nameStr;//姓名
    NSString *_localString;//定位的信息
    NSString *_placeString;//手动输入地址
    NSString *_phoneString;//电话
    NSString *_noteString;//备注信息
    NSMutableArray *_standardArr;//国标
    NSMutableArray *_costArr;//配送费用
    NSMutableArray *_userInfoArr;//用户数据
    NSMutableArray *_addressArr;
    NSString *_standardString;//国标提交参数
    NSString *_oilTypeStr;//国三，国五
    
    BOOL twoBool,threeBool,fourBool,fiveBool,sixBool,sevenBool;
    
    NSArray *_cMoneyArr;
    
    NSMutableArray *_timeDataArr;//时间
    UIView * imageView;
    
    NSArray *checkImageArr;//油品检测照片
    
    NSString * _availableBalanceStr;//资产
    
    NSString * _priceStr;//油品单价
    
    NSString * _moneyString;//加油金额
    
    NSString * _costStr;//配送费用
    
    NSString * _orderAmount;//订单金额
}

- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;

    }
    return self;
}

- (void)dealloc{
    CLog(@"销毁了");
}
// 参数类型是NSNotification

- (void)gainAddressNotification:(NSNotification *)notification{
    
    NSLog(@"接受到通知，改变用户地址");
    self.userAddress = notification.userInfo ;
    NSLog(@"userAddress:%@",self.userAddress);
    _cityStr = [NSString stringWithFormat:@"%@",[self.userAddress objectForKey:@"city"]];
    _districtStr = [NSString stringWithFormat:@"%@",[self.userAddress objectForKey:@"district"]];
    _placeString = [NSString stringWithFormat:@"%@",[self.userAddress objectForKey:@"address"]];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"完善订单信息";
    

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gainAddressNotification:) name:@"gainAddressNotification" object:nil];
   [self CheckAddressBookAuthorization:^(bool isAuthorized, bool isUp_ios_9) {
       
       FileManager * fileManager = [[FileManager alloc]init];
       //初始化一个FileManager
       MessageObject * messageObject = [[MessageObject alloc]init];
       messageObject.userInfo = _userInfoArr;
       [fileManager storgaeObject:messageObject];
   }];
    
    _timeDataArr = [NSMutableArray array];
    _standardArr = [NSMutableArray array];
    _costArr = [NSMutableArray array];
    _userInfoArr = [NSMutableArray array];
    _noteString = @"";
    _moneyString = @"";
    _spacing = 15;//间距
    _W = (kScreenWidth-60)/3;//一个按钮的宽度
    
    _selIndex = -1;//默认三个button的未选中状态
    _cMoneyArr = @[@"￥500.00",@"￥1000.00",@"加满"];
    [self setupForDismissKeyboard];//释放键盘
    _titleArr = @[@[@"加油地点",@""],@[@"柴油标准"],@[@"加油金额"],@[@"余额"],@[@"到达时间"],@[@"联系人"],@[@"联系电话"],@[@"备注信息"]];
    [self createTableView];
    [self createUI];
    [self gainLocationServicesEnable];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    CaptchaTimerManager *manager = [CaptchaTimerManager sharedTimerManager];
    int temp = manager.timeout;
    [self timerCountDowntimerCountDownWithTime:temp];
}

//计时器处理
- (void)timerCountDowntimerCountDownWithTime:(int)time {
    _timeout = time;
    dispatch_queue_t queue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    
    dispatch_source_t _timer =
    dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,
                           0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);
    //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(_timeout<=0){//倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //这里写倒计时结束button的处理
                _rightButton.enabled =YES;
                [_rightButton setBackgroundColor:[QColorUtility defaultBlueColor]];
                 dispatch_source_cancel(_timer);
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //这里写倒计时期间button的处理（重设button的tiitle、用户交互等）
                _rightButton.enabled = NO;
                NSString *countDownString = [NSString stringWithFormat:@"提交订单(倒计时%d秒)",_timeout];
                [_rightButton setTitle:countDownString forState:UIControlStateDisabled];
                [_rightButton setBackgroundColor:[UIColor darkGrayColor]];
            });
            _timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

- (void)createUI{
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, _tableView.bottom, 130, 50)];
    leftView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:leftView];
    
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 130, 1)];
    lineView.backgroundColor = self.view.backgroundColor;
    [leftView addSubview:lineView];
    
    _titleLabel = [QViewUtility createLabelWithFrame:CGRectMake(15, 15, 38, 20) font:Ksize16 textAlignment:NSTextAlignmentLeft textColor:[QColorUtility defaultBackColor] text:@"油价:"];
    [leftView addSubview:_titleLabel];
    
    _leftLabel = [QViewUtility createLabelWithFrame:CGRectMake(_titleLabel.right+1, 15, 75, 20) font:16 textAlignment:NSTextAlignmentLeft textColor:[QColorUtility defaultRedColor] text:@""];
    [leftView addSubview:_leftLabel];
    
    _loadingV = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(_titleLabel.right+5, 15, 20, 20)];
    _loadingV.color = [UIColor grayColor];
    [leftView addSubview:_loadingV];
    
    _rightButton = [QViewUtility createButtonWithFrame:CGRectMake(_leftLabel.right, _tableView.bottom, kScreenWidth-129, 50) font:Ksize17 title:@"提交订单" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [_rightButton blueStyle];
    [_rightButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
     [_rightButton setTitle:@"不能点击" forState:UIControlStateDisabled];
    [self.view addSubview:_rightButton];
    
    _phoneString = [QUserInfo sharedInfo].loginModel.lastOrderPhone;
    
    if (_phoneString.length == 0) {
        _phoneString = [QUserInfo sharedInfo].loginModel.tel;
    }
    
    if(_phoneString.length > 0){
        fiveBool = YES;
    }else{
        fiveBool = NO;
    }
    
    _nameStr = [QUserInfo sharedInfo].loginModel.lastOrderName;
    
    if (_nameStr.length == 0) {
        _nameStr = [QUserInfo sharedInfo].loginModel.nickName;
    }
    
    
}

#pragma mark -- 判断app定位是否开启
- (void)gainLocationServicesEnable{
    
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        
        //定位功能可用
         [self requestAddressData];
        
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        
         [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"未开启定位 请到设置>隐私>定位 打开本应用的权限设置" btnTitle:@"我已知晓" type:1 myBlock:^{
         [self.navigationController popViewControllerAnimated:YES];
         
         }];
        
        //定位不能用
//        [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"请开启定位" leftTitle:@"取消" rightTitle:@"确定" type:1 myBlock:^(NSInteger tag) {
//            if(tag == 1){
//                
//                if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.000000) {
//                    //跳转到定位权限页面
//                    
//                    [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"请到设置>隐私>定位 打开本应用的权限设置" btnTitle:@"我已知晓" type:1 myBlock:^{}];
////                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
////                    if( [[UIApplication sharedApplication]canOpenURL:url] ) {
////                        [[UIApplication sharedApplication] openURL:url];
////                    }
//                }else {
//                    //跳转到定位开关界面
////                    NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
////                    if( [[UIApplication sharedApplication]canOpenURL:url] ) {
////                        [[UIApplication sharedApplication] openURL:url];
////                    }
//                }
//            }else{
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//
//        }];
    }
}
#pragma mark --- 是否有订单未支付
//- (void)requestNoPayOrderData{
//    NSString *url = [QParamService urlWithAction:@"getOrderStateNum"];
//    NSDictionary *param = [QParamService noPayOrder];
//    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
//        if(error){
//            return;
//        }
//        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
//        if([basModel.result isEqualToString:@"success"]){
//            QNoPayOrderModel * model = [QNoPayOrderModel objectFromDict:basModel.items];
//            if ([model.num isEqualToString:@"0"]) {
//                [QUserInfo sharedInfo].unPayOrder = NO;
//                
//            }else{
//                [QUserInfo sharedInfo].unPayOrder = YES;
//                [QUserInfo sharedInfo].unPayCount = [NSString stringWithFormat:@"%@",model.num];
//               
//                QTopupMoneyVC * vc = [[QTopupMoneyVC alloc] init];
//                [self.navigationController pushViewController:vc animated:YES];
//            }
//        }else{
//        }
//    }];
//}

- (void)ForbidRepeatOrderWithButton:(UIButton *)button{
    
    NSLog(@"button:%@",button);
}
#pragma mark --- createTableView
- (void)createTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-50) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView registerNib:[UINib nibWithNibName:@"QPerfectOrderInforMationCell" bundle:nil] forCellReuseIdentifier:@"QPerfectOrderInforMationCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QPerfectTextViewCell" bundle:nil] forCellReuseIdentifier:@"QPerfectTextViewCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QOilStandardCell" bundle:nil] forCellReuseIdentifier:@"QOilStandardCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QPerfectOrderMoneyCell" bundle:nil] forCellReuseIdentifier:@"QPerfectOrderMoneyCell"];
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_titleArr[section]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    __weak QPerfectOrderInforMationVC *wSelf = self;

    if(indexPath.section == 7){
        QPerfectTextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QPerfectTextViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.block = ^(NSString *str){
        __strong QPerfectOrderInforMationVC *sSelf = wSelf;
            sSelf->_noteString = str;
        };
        return cell;
    }else if (indexPath.section == 1){//国标
        QOilStandardCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QOilStandardCell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.arr = _standardArr;
        return cell;
    }else if (indexPath.section == 3){//资产
        QPerfectOrderMoneyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QPerfectOrderMoneyCell" forIndexPath:indexPath];
        cell.availableBalanceStr = _availableBalanceStr;
        cell.priceStr = _priceStr;
        
        return cell;
    }else{
    
        QPerfectOrderInforMationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QPerfectOrderInforMationCell" forIndexPath:indexPath];
        cell.indexPath = indexPath;
        cell.showKeyBoard = _showKeyBoard;
        cell.addOilTimeStr = _paramStr;
        cell.placeStr = [NSString stringWithFormat:@"%@ %@",_cityStr,_districtStr];
        cell.addressStr = _placeString;
        cell.telStr = _phoneString;
        cell.nameStr = _nameStr;
        cell.sendCostStr = _costStr;
        //if (indexPath.section == 2) {
            //国四国五加油金额  国五：500 国四:1000
            // [cell setCellWithData:_orderAmount];
        //}
       
        
        if(_localString.length > 0){
            threeBool = YES;
        }else{
            threeBool = NO;
        }
        if(_placeString.length > 0){
            fourBool = YES;
        }else{
            fourBool = NO;
        }
        cell.nameStr = _name;
        
        //通讯录
        if (indexPath.section == 5) {
            cell.delegate = self;
            cell.textField.text = _name;
            if ([_name isEqualToString:@""]||_name == nil) {
                
            }else{
                _nameStr = _name;
            }
            cell.textField.text = _nameStr;
        }
        if (indexPath.section == 6) {
            
            if ([_phone isEqualToString:@""]||_name == nil) {
                
            }else{
                _phoneString = _phone;
            }
            cell.textField.text = _phoneString;
        }

    
        cell.FieldBlock = ^(NSString *str,NSInteger tag){
            __strong QPerfectOrderInforMationVC *sSelf = wSelf;
            if(tag == 1){//加油金额
                sSelf->_moneyString = str;
            }else if (tag == 2){//输入的地址
                sSelf->_placeString = str;
                if(sSelf->_placeString.length >0){
                    sSelf->fourBool = YES;
                }else{
                    sSelf->fourBool = NO;
                }
            }else if (tag == 3){//手机电话
                sSelf->_phoneString = str;
                //[QUserInfo sharedInfo].loginModel.lastOrderPhone = str;
                if(sSelf->_phoneString.length == 11){
                    sSelf->fiveBool = YES;
                }else{
                    sSelf->fiveBool = NO;
                }
            }else if (tag == 4){
                sSelf->_nameStr = str;
            }
        };
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(void)AddressBookDelegateAction
{
    NSLog(@"dadada");
    [self JudgeAddressBookPower];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
     FileManager * fileManager = [[FileManager alloc]init];
        //初始化一个FileManager
    MessageObject * messageObject = [[MessageObject alloc]init];
    messageObject.userInfo = _userInfoArr;
    [fileManager storgaeObject:messageObject];
}
#pragma mark ---- 调用系统通讯录
- (void)JudgeAddressBookPower {
    ///获取通讯录权限，调用系统通讯录
    [self CheckAddressBookAuthorization:^(bool isAuthorized , bool isUp_ios_9) {
        if (isAuthorized) {
            [self callAddressBook:isUp_ios_9];
        }else {
            /*[QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"未开启定位 请到设置>隐私>通讯录 打开本应用的权限设置" btnTitle:@"我已知晓" type:1 myBlock:^{
                [self.navigationController popViewControllerAnimated:YES];
                
            }];*/

            
            
        }
    }];
}
- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized , bool isUp_ios_9))block {
    if (Is_up_Ios_9)) {
        CNContactStore * contactStore = [[CNContactStore alloc]init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * __nullable error) {
                if (error)
                {
                    NSLog(@"Error: %@", error);
                }
                else if (!granted)
                {
                    
                    block(NO,YES);
                }
                else
                {
                    block(YES,YES);
                }
            }];
        }
        else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){
            
            block(YES,YES);
            //创建联系人仓库
            CNContactStore *store = [[CNContactStore alloc] init];
            //获取通讯录数据
            // 创建联系人的请求对象
            // keys决定这次要获取哪些信息,比如姓名/电话
            NSArray *fetchKeys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
            CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];
            // 3.3.请求联系人
            NSError *error = nil;
            [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
                // stop是决定是否要停止
                // 1.获取姓名
                NSString *firstname = contact.givenName;
                NSString *lastname = contact.familyName;
                NSLog(@"%@ %@", firstname, lastname);
                NSString *tmpName = [firstname stringByAppendingString:lastname];
                NSString *name = [tmpName stringByAppendingString:@"="];
                //2.获取电话号码
                NSArray *phones = contact.phoneNumbers;
                // 3.遍历电话号码
                NSString *phone = @"";
                for (CNLabeledValue *labelValue in phones) {
                    CNPhoneNumber *phoneNumber = labelValue.value;
                    NSLog(@"%@ %@", phoneNumber.stringValue, labelValue.label);
                    phone = phoneNumber.stringValue;
                }
                NSLog(@"name:%@%@ %@",firstname,lastname,phone);
                NSString *userInfo = [name stringByAppendingString:phone];
                [_userInfoArr addObject:userInfo];
            }];
        }
        else {
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
        }
    }else {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        
        if (authStatus == kABAuthorizationStatusNotDetermined)
        {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error)
                    {
                        NSLog(@"Error: %@", (__bridge NSError *)error);
                    }
                    else if (!granted)
                    {
                        
                        block(NO,NO);
                    }
                    else
                    {
                        block(YES,NO);
                    }
                });
            });
        }else if (authStatus == kABAuthorizationStatusAuthorized)
        {
            if (Is_up_Ios_10)) {
                //创建联系人仓库
                CNContactStore *store = [[CNContactStore alloc] init];
                //获取通讯录数据
                // 创建联系人的请求对象
                // keys决定这次要获取哪些信息,比如姓名/电话
                NSArray *fetchKeys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
                
                CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];
                // 3.3.请求联系人
                NSError *error = nil;
                [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
                    // stop是决定是否要停止
                    // 1.获取姓名
                    NSString *firstname = contact.givenName;
                    NSString *lastname = contact.familyName;
                    NSLog(@"%@ %@", firstname, lastname);
                    
                    // 2.获取电话号码
                    NSArray *phones = contact.phoneNumbers;
                    
                    // 3.遍历电话号码
                    for (CNLabeledValue *labelValue in phones) {
                        CNPhoneNumber *phoneNumber = labelValue.value;
                        NSLog(@"%@ %@", phoneNumber.stringValue, labelValue.label);
                    }
                }];
                block(YES,NO);
            }
           
        }else {
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
            
        }
    }
}

- (void)callAddressBook:(BOOL)isUp_ios_9 {
    if (isUp_ios_9) {
        CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
        contactPicker.delegate = self;
        contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [self presentViewController:contactPicker animated:YES completion:nil];
    }else {
        ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
        peoplePicker.peoplePickerDelegate = self;
        [self presentViewController:peoplePicker animated:YES completion:nil];
    }
}

#pragma mark --  CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];
        /// 电话
        NSString *text2 = phoneNumber.stringValue;
        //        text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
        _name = text1;
        _phone = text2;
        [self.tableView reloadData];
    }];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    CFStringRef anFullName = ABRecordCopyCompositeName(person);
    
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@",anFullName];
        /// 电话
        NSString *text2 = (__bridge NSString*)value;
        //        text2 = [text2 stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
        _name = text1;
        _phone = text2;
        [self.tableView reloadData];    
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 7){
        return 100;
    }else if (indexPath.section == 1){
        return 60;
    }else{
        return 50;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 3){
        return 120;
    }else{
        return 0.01;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 3) {
    
        imageView = [[UIView alloc] initWithFrame:CGRectMake(0, 2, kScreenWidth, 116)];
        NSArray *array = @[@"检测报告",@"油品小样"];
        for (int i = 0; i<2; i++) {
            
            UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(15 + (kScreenWidth - 40)/2 * i + i * 10, 2, (kScreenWidth - 40)/2, 116)];
            [imageView addSubview:image];
            image.tag = i;
            image.contentMode=UIViewContentModeScaleAspectFill;
            image.layer.cornerRadius = 6;
            image.clipsToBounds = YES;
            image.userInteractionEnabled=YES;
            [image addGestureRecognizer:[self singleTapGestureRecognizer]];
            
            UIView *coverView = [[UIView alloc]initWithFrame:image.bounds];
            coverView.alpha = 0.6f;
            coverView.backgroundColor = [UIColor blackColor];
            image.userInteractionEnabled = YES;
            [image addSubview:coverView];
            
            UILabel *label = [[UILabel alloc]initWithFrame:image.bounds];
            label.text = [array objectAtIndex:i];
            [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
            label.textColor = [UIColor whiteColor];
            label.textAlignment = UITextAlignmentCenter;
            [image addSubview:label];
            
            if (checkImageArr.count) {
                NSString *url = checkImageArr[i];
                [image sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"mainPlace_image"]];

            }

        }
        return imageView;
    }else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 4 && indexPath.row == 0){
        if ([_paramStr isEqualToString:@"该区域暂无配置时间"]) {
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"该区域暂无配置时间" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            return;
        }
        __block QPerfectOrderInforMationVC *wSelf = self;
        if (_timeDataArr.count){
            QDatePickView *dateView = [[QDatePickView alloc] init];
            dateView.dateArr = _timeDataArr;
            dateView.dateBlock = ^(NSString *str,NSString *time){
                wSelf.paramStr = str;
                NSArray *array = [str componentsSeparatedByString:@"-"];
                NSString *dateString = [NSString stringWithFormat:@"%@-%@",[array objectAtIndex:1],[array objectAtIndex:2]];
                if (dateString.length>0) {
                    _costStr = @"";
                    for (QSendCostModel *model in _costArr) {
                        if ([dateString isEqualToString:model.time]) {
                            _costStr = [NSString stringWithFormat:@"(%@%@元)",model.explain,model.freightPrice];
                        }
                    }
                    
                }
                _showKeyBoard = NO;
                
                [wSelf->_tableView reloadData];
                
                if (wSelf.paramStr.length>0) {
                    
                    twoBool = YES;
                    
                }else{
                    
                    twoBool = NO;
                    
                }
                
            };
            
            [dateView showPickView];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"请先选择加油地点" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
        
    }else if (indexPath.section ==0 && indexPath.row == 0){
        
        WS(wSelf);
        
        QChooseAddressVC * vc = [[QChooseAddressVC alloc] init];
        
        vc.block = ^(QHistoryAddressModel * model){
            
            __strong QPerfectOrderInforMationVC * sSelf = wSelf;
            
            if (model.address == nil) {
                _localString = @"";
            }else{
                sSelf->_localString =model.localString;
            }
            sSelf->_showKeyBoard = NO;
            sSelf->_cityStr = model.city;
            
            sSelf->_districtStr = model.limitArea;
            
            //地址重新选择，国标与时间需要重新选择
            sSelf->_standardString = @"";
            sSelf->sixBool = NO;
            //时间
            sSelf->_paramStr = nil;
            
            
            sSelf->_placeString = model.address;
            sSelf->_lat = model.y;
            sSelf->_lon = model.x;
            
            
            [sSelf->_tableView reloadData];
            
            if(sSelf->_localString.length > 0){
                sSelf->threeBool = YES;
            }else{
                sSelf->threeBool = NO;
            }
            if(sSelf->_placeString.length > 0){
                sSelf->fourBool = YES;
            }else{
                sSelf->fourBool = NO;
            }
            
            if (model.address == nil) {
                return ;
            }
            [wSelf requestOrderInfo];
            
        };
        
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

#pragma mark - private
- (UITapGestureRecognizer*)singleTapGestureRecognizer {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imgViewTapped:)];
    return tapGesture;
}

#pragma mark - Event
- (void)imgViewTapped:(UITapGestureRecognizer*) tapGestureRecognizer {
    HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
    browserVc.sourceImagesContainerView = imageView; // 原图的父控件
    
    NSArray *imgArr = [NSArray array];
    if (_standardArr.count) {
        for (QStandardModel * model in _standardArr) {
            if (model.select == YES) {
                imgArr = [NSArray arrayWithObjects:model.justImg, model.backImg,nil];
            }
        }
    }
    browserVc.imageCount = imgArr.count; // 图片总数
    browserVc.currentImageIndex = (int)tapGestureRecognizer.view.tag;
    browserVc.delegate = self;
    [browserVc show];
}

#pragma mark - photobrowser代理方法
- (UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    UIImage *img = [imageView.subviews[index] image];
    if (!img) {
        return [UIImage imageNamed:@"mainPlace_image"];
    }
    return img;
}

- (NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    NSArray *imgArr = [NSArray array];
    if (_standardArr.count) {
        for (QStandardModel * model in _standardArr) {
            if (model.select == YES) {
                imgArr = [NSArray arrayWithObjects:model.justImg, model.backImg,nil];
            }
        }
    }

    return [NSURL URLWithString:imgArr[index]];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _showKeyBoard = NO;
    [_tableView endEditing:YES];
}



#pragma mark --- 获取历史地址
- (void)requestAddressData{
    WS(wSelf);
    NSString * url = [QParamService urlWithAction:@"getHistoryAddress"];
    NSDictionary * para = [QParamService getHistoryAddress];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:wSelf.view];
        if (error) {
            return ;
        }
        QBaseModel * baseModel = [QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            _addressArr = [QHistoryAddressModel mj_objectArrayWithKeyValuesArray:[baseModel.items objectForKey:@"historys"]];
            if (_addressArr.count) {
                QHistoryAddressModel * model = [_addressArr objectAtIndex:0];
                _cityStr = model.city;
                _districtStr = model.limitArea;
                _lat = model.y;
                _lon = model.x;
                if ([model.address containsString:model.city]) {
                    model.address = [model.address stringByReplacingOccurrencesOfString:model.city withString:@""];
                }
                if ([model.address containsString:model.limitArea]) {
                    model.address = [model.address stringByReplacingOccurrencesOfString:model.limitArea withString:@""];
                }
                _placeString = model.address;
                _localString = [NSString stringWithFormat:@"%@%@",model.city,model.limitArea];
                if(_localString.length > 0){
                    threeBool = YES;
                }else{
                    threeBool = NO;
                }
                if(_placeString.length > 0){
                    fourBool = YES;
                }else{
                    fourBool = NO;
                }
                
                [_tableView reloadData];

            }else{
                if([QUserInfo sharedInfo].cityStr.length > 0){
                    _cityStr = [QUserInfo sharedInfo].cityStr;
                    _districtStr = [QUserInfo sharedInfo].districtStr;
                    _lat = [QUserInfo sharedInfo].lat;
                    _lon = [QUserInfo sharedInfo].lon;
                    _localString = [NSString stringWithFormat:@"%@%@",_cityStr,_districtStr];
                    _placeString = [QUserInfo sharedInfo].address;

                }else{
                    self.titleLabel.frame = CGRectMake(15, 15, 90, 20);
                    self.titleLabel.text = @"未开通服务";
                }
                [_tableView reloadData];

                
            }

            [self requestOrderInfo];
            
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (void)standardAction:(NSInteger)tag{
    if (_standardArr.count) {
        QStandardModel * model = [_standardArr objectAtIndex:tag - 1];
        for (QStandardModel * model1 in _standardArr) {
            if ([model1.oilTypeId isEqualToString:model.oilTypeId]) {
                model1.select = YES;
                _standardString = model1.oilTypeId;
                _oilTypeStr = model.oilType;
                sixBool = YES;
                checkImageArr = [NSArray arrayWithObjects:model1.justImg,model1.backImg, nil];

                [self OilPriceByStandardWithModel:model1];
            }else{
                model1.select = NO;
            }
        }
    }
    
    [_tableView reloadData];
}

#pragma mark --- 订单完整信息
- (void)requestOrderInfo{
    WS(wself);
    [_standardArr removeAllObjects];
    NSString * url = [QParamService urlWithAction:@"/order/getSaveOrderInformation"];
    NSDictionary * parat = [QParamService getSaveOrderInformationWithCity:_cityStr Area:_districtStr];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:parat completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error) {
            return ;
        }
        QBaseModel * baseModel = [QBaseModel objectFromDict:dict];
        if ([baseModel.result isEqualToString:@"success"]) {
            
            //资产
            _availableBalanceStr = [baseModel.items objectForKey:@"availableBalance"];
            _standardArr = [QStandardModel mj_objectArrayWithKeyValuesArray:[baseModel.items objectForKey:@"fuelList"]];
            _orderAmount = [baseModel.items objectForKey:@"orderAmount"];
            if ([_availableBalanceStr floatValue]<[_orderAmount floatValue]) {
                sevenBool = NO;
            }else{
                sevenBool = YES;
            }
            
            //国标
            if (_standardArr.count) {
                for (QStandardModel * model in _standardArr) {
                    if ([model.oilType isEqualToString:@"国五"]) {
                        model.select = YES;
                        _standardString = model.oilTypeId;
                        _oilTypeStr = model.oilType;
                        
                        sixBool = YES;
                        
                        checkImageArr = [NSArray arrayWithObjects:model.justImg,model.backImg, nil];

                        //油价
                        [wself OilPriceByStandardWithModel:model];
                    }else{
                        model.select = NO;
                    }
                }
            }
            
            //配送费用
            _costArr = [QSendCostModel mj_objectArrayWithKeyValuesArray:[baseModel.items objectForKey:@"frdightList"]];
            
                    
            
            //时间
            [self OilTimeWithBaseModel:baseModel];


            [_tableView reloadData];

        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:baseModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];

}

- (void)OilPriceByStandardWithModel:(QStandardModel *)model{
    if(model.price.length > 0){
        self.titleLabel.frame = CGRectMake(15, 15, 38, 20);
        self.leftLabel.text = [NSString stringWithFormat:@"%@/升",model.price];
        _priceStr = model.price;
        self.titleLabel.text = @"油价:";
    }else{
        self.titleLabel.text = @"暂未开通";
        self.titleLabel.frame = CGRectMake(15, 15, 90, 20);
        self.leftLabel.text = @"";
    }

}
//时间
- (void)OilTimeWithBaseModel:(QBaseModel *)model{
    
    [_timeDataArr removeAllObjects];
    NSDictionary *ds = model.items;
    NSMutableDictionary *d1 = [NSMutableDictionary dictionary];
    NSString *today = ds[@"today"];
    NSString *todayData = ds[@"todayTime"];
    NSArray *todayArr = [todayData componentsSeparatedByString:@","];
    [d1 setObject:today forKey:@"name"];
    [d1 setObject:todayArr forKey:@"dates"];
    
    NSMutableDictionary *d2 = [NSMutableDictionary dictionary];
    NSString *tomorrow = ds[@"tomorrow"];
    NSString *tomorrowData = ds[@"tomorrowTime"];
    NSArray *tomorrowArr = [tomorrowData componentsSeparatedByString:@","];
    [d2 setObject:tomorrow forKey:@"name"];
    [d2 setObject:tomorrowArr forKey:@"dates"];
    
    [_timeDataArr addObject:d1];
    [_timeDataArr addObject:d2];
    
    
    if (![todayData isEqualToString:@""]) {
        _paramStr =[NSString stringWithFormat:@"%@-%@", today,[[todayData componentsSeparatedByString:@","] objectAtIndex:0]];
        NSString *str = [[todayData componentsSeparatedByString:@","] objectAtIndex:0];
        for (QSendCostModel *model in _costArr) {
            if ([str isEqualToString:model.time]) {
                _costStr = [NSString stringWithFormat:@"%@%@元",model.explain,model.freightPrice];
            }
        }
        twoBool = YES;
    }else{
        _paramStr = [NSString stringWithFormat:@"%@-%@",tomorrow,[[tomorrowData componentsSeparatedByString:@","] objectAtIndex:0]];
        NSString *str = [[todayData componentsSeparatedByString:@","] objectAtIndex:0];
        for (QSendCostModel *model in _costArr) {
            if ([str isEqualToString:model.time]) {
                _costStr = [NSString stringWithFormat:@"%@%@元",model.explain,model.freightPrice];
            }
        }

        twoBool = YES;
    }
    
    if ([todayData isEqualToString:@""]&&[tomorrowData isEqualToString:@""]) {
        _paramStr = @"该区域暂无配置时间";
        twoBool = NO;
    }
}

#pragma mark --- 提交订单  ----
- (void)buttonAction:(UIButton *)button{
    
    //    [self requestNoPayOrderData];
    NSString *titleStr;
    if( twoBool && threeBool && fourBool && fiveBool&&sixBool){
        
        if (sevenBool) {
            
            QSubmitOrderModel * model = [[QSubmitOrderModel alloc] init];
            model.lon = _lon;
            model.lat = _lat;
            model.time = _paramStr;
            model.limitArea = _districtStr;
            model.address = _placeString;
            model.remark = _noteString;
            model.city = _cityStr;
            model.flag = @"";
            model.oilTypeId = _standardString;
            model.tel = _phoneString;
            model.name = _nameStr;
            model.price = _priceStr;
            model.oilType = _oilTypeStr;
            model.total = _moneyString;
            model.costStr = _costStr;
            
            
            QConfirmOrderInforMationVC *vc = [[QConfirmOrderInforMationVC alloc] init];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            
            NSString *titleStr = @"";
            for (QStandardModel *model in _standardArr) {
                if (([model.oilType isEqualToString:@"普柴"]||[model.oilTypeId isEqualToString:@"120"])&&model.select == YES) {
                    if ([_availableBalanceStr intValue]<1000) {
                        titleStr = @"您的余额不足1000,请充值";
                    }
                }
            }
            
            for (QStandardModel *model in _standardArr) {
                
                if ([model.oilType isEqualToString:@"国五"]) {
                    titleStr = @"您的余额不足500,请充值";
                }
            }
            
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:titleStr leftTitle:@"取消" rightTitle:@"确定" type:1 myBlock:^(NSInteger tag) {
                if(tag == 1){
                    QTopupMoneyVC * vc = [[QTopupMoneyVC alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    
                }
            }];
            
        }
        
    }else{
        
        if (!threeBool) {
            titleStr = @"请选择加油地点";
        }else if (!fourBool){
            titleStr = @"请填写加油地址";
        }else if (!sixBool){
            titleStr = @"请填写国际标准";
        }else if (!twoBool){
            titleStr = @"该区域未配置时间";
        }else if (!fiveBool){
            titleStr = @"请填写现场联系人手机";
        }
        
        [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:titleStr btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
    }
}


@end
